package com.meaningful.thinking.nio_demo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Main {

    public static void main(String[] args) {

    }

    public static void fastCopy(String src, String dist) throws Exception {

        /* 获得源文件的输入字节流 */
        FileInputStream sourceFileInputStream = new FileInputStream(src);

        /* 获取输入字节流的文件通道 */
        FileChannel sourceFileChannel = sourceFileInputStream.getChannel();

        /* 获取目标文件的输出字节流 */
        FileOutputStream targetFileOutputStream = new FileOutputStream(dist);

        /* 获取输出字节流的通道 */
        FileChannel targetFileChannel = targetFileOutputStream.getChannel();

        /* 为缓冲区分配 1024 个字节 */
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

        while (true) {

            /* 从输入通道中读取数据到缓冲区中 */
            int readed = sourceFileChannel.read(buffer);

            /* read() 返回 -1 表示 EOF */
            if (readed == -1) {
                break;
            }

            /* 切换读写 */
            buffer.flip();

            /* 把缓冲区的内容写入输出文件中 */
            targetFileChannel.write(buffer);

            /* 清空缓冲区 */
            buffer.clear();

        }

    }

}
